package com.weyoung.app.interceptor;


import cn.dev33.satoken.stp.StpUtil;
import com.weyoung.app.event.AccessEvent;
import com.weyoung.common.config.RabbitMQConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AccessStatsInterceptor implements HandlerInterceptor {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            // 获取当前登录用户ID
            Integer loginId = (Integer) StpUtil.getLoginId();
            // 创建访问事件
            AccessEvent event = AccessEvent.from(request, loginId);
            // 发送消息到RabbitMQ队列
            rabbitTemplate.convertAndSend(RabbitMQConfig.STATS_QUEUE, event);
        } catch (Exception e) {
            // 记录异常但不影响正常业务
            e.printStackTrace();
        }
        return true;
    }
} 